package com.example.myapplication;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView, popRecyclerView;
    private RecyclerAdapter recyclerAdapter;
    PopRecyclerAdapter popRecyclerAdapter;
    List<Video> videoList;
    TextView textView;
    List<List<Video>> listList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        tv_flag = findViewById(R.id.tv_flag);
        videoList = new ArrayList<>();
        context = MainActivity.this;
        //1.先请求判断是否具有对应权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        //根据返回的结果，判断对应的权限是否有。
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }
        //从本地的Sdcard获取数据
        getDataFromLocal();

    }


    int wh;

    //初始化
    private void initView() {


        textView = findViewById(R.id.tv_title);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNoneEffect();
            }
        });
        recyclerView = findViewById(R.id.rv);
        //recyclerView.addItemDecoration(new DividerItemDecorations());
        recyclerView.addItemDecoration(new DividerItemDecorations(MainActivity.this, LinearLayoutManager.VERTICAL));
        // 线性布局管理器
        // LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        //recyclerView.setLayoutManager(linearLayoutManager);

        GridLayoutManager manager = new GridLayoutManager(this, 4);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        //适配器


        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        wh = width / 4;
        Log.e(width + "width/4", "" + wh);


    }

    private Context context;
    private Video video;
    private TextView tv_flag;
    private int flag;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (videoList != null && videoList.size() > 0) {
                //有数据，设置适配器
              /*  videoAdapter=new VideoAdapter(videoList,MainActivity.this);
                lv_list.setAdapter(videoAdapter);*/

                recyclerAdapter = new RecyclerAdapter(videoList, wh);
                recyclerView.setAdapter(recyclerAdapter);
                recyclerAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        //  Toast.makeText(MainActivity.this, "click " + position, Toast.LENGTH_SHORT).show();
                        Video video = videoList.get(position);
                        Log.i("Aye", video.toString());
                        //调用自己写的播放器
                        Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                        intent.setDataAndType(Uri.parse(video.getPath()), "video/*");
                        startActivity(intent);

                        // File parentFile = new File(path).getParentFile();


                    }
                });
                flag = 8;
                tv_flag.setVisibility(flag);

               // getFiles(parentFile.getPath());
               // getAllFileName(path,listpath);
            } else {
                //没有数据
                flag = 0;
                tv_flag.setVisibility(flag);

            }
        }
    };
    String path;
    File parentFile;
    Bitmap bitmap;


    //从本地的Sdcard获取数据
    private void getDataFromLocal() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                //获取内容提供者
                ContentResolver contentResolver = context.getContentResolver();
                //视频uri
                Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                //需要获取的视频信息
                String[] strings = {
                        MediaStore.Video.Media.DISPLAY_NAME,  //视频在文件sdcard的名称
                        MediaStore.Video.Media.SIZE,  //视频大小
                        MediaStore.Video.Media.DURATION,  //视频总时长
                        MediaStore.Video.Media.DATA  //视频路径
                };

                //查询数据
                Cursor cursor = contentResolver.query(uri, strings, null, null, null);

                Log.i("--------------", arrayList.size() + "" + cursor.getCount());
                if (cursor != null) {
                    while (cursor.moveToNext()) {

                        String name = cursor.getString(0);
                        long duration = cursor.getLong(1);
                        long size = cursor.getLong(2);
                        path = cursor.getString(3);
                        //  Bitmap bitmap =  getBit(path);
                        // bitmap =  getVideoThumbnail(path,wh,wh,MediaStore.Images.Thumbnails.MINI_KIND);

                        Log.e("path----", path);
                        video = new Video(name, size, duration, path);
                        videoList.add(video);
                        parentFile = new File(path).getParentFile();
                          Log.e( parentFile .toString()+"path-=---", parentFile.getName().toString());
                        String parentFileName = parentFile.getName();
                        if(!arrayList.contains(parentFileName))
                        {
                            arrayList.add(parentFileName);


                        }

                        if(!arrayListp.contains(parentFile.toString()))
                        {
                            arrayListp.add(parentFile.toString());


                        }







                        //  FlieVideo flieVideo = new FlieVideo(,"","");
                    }



                  //  Log.e("path----", arrayList.size());
                    cursor.close();
                }
                //发消息


                //LinkedHashSet hashSet = new LinkedHashSet<>(arrayList);
                //listWithoutDuplicates = new ArrayList<>(hashSet);


                //getFiles(arrayList.get(1).toString());

                Log.e("path-66666---",getFiles("/storage/emulated/0/DCIM/Camera").size()+"");
  handler.sendEmptyMessage(1);


            }
        }.start();




    }
    List<List<String>> l = new ArrayList<>();

    ArrayList<String> listpath  = new ArrayList<>();
    //获取所有文件
    public static void getAllFileName(String path, ArrayList<String> list) {
        File file = new File(path);
        //获取全部File
        //返回目录名加文件名
        //添加过滤器
        String[] strings = file.list();
        for (String string : strings) {
            Log.e("","string"+string);
           // System.out.println(string);
        }
        //这些路径名表示此抽象路径名所表示目录中的文件。
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return true;
            }
        });
        for (int i = 0; i < files.length; i++) {
            //判断是否是目录，是的话继续递归
            if (files[i].isDirectory()) {
                getAllFileName(files[i].getAbsolutePath(), list);
            } else {
                //否则添加到list
                //获取全部文件名
                list.add(files[i].getName());
                //获取全部包+文件名
                //list.add(files[i].getAbsolutePath());
            }
        }
    }

    /**
     * @Author：
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     * @Date：
     */

    public static List<String> getFiles(String path1) {
        List<String> files = new ArrayList<String>();
        File file = new File(path1);
        File[] tempList = file.listFiles();
        int k =0;
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                String s = tempList[i].getName();
                String result = s.substring(s.length()-4,s.length());
                if (result.equals(".mp4")){
                    k++;
                    Log.e(k+"path-111---",i+""+s);
                }


            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }
    List<String> listn = new ArrayList<>();
    List<List<String>> lb = new ArrayList<>();
    List listWithoutDuplicates;
    List<String> arrayList = new ArrayList();
    List<String> arrayListp = new ArrayList();
    FlieVideo flieVideo;
    List<String> fdList = new ArrayList();

    PopupWindow popupWindow;


    private void showNoneEffect() {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vPopupWindow = inflater.inflate(R.layout.popupwindow, null, false);//引入弹窗布局
        popupWindow = new PopupWindow(vPopupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);

        popRecyclerView = vPopupWindow.findViewById(R.id.pop_rv);

        popRecyclerView.addItemDecoration(new DividerItemDecorations(MainActivity.this, LinearLayoutManager.VERTICAL));
        // 线性布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        popRecyclerView.setLayoutManager(linearLayoutManager);
//        Log.e("",""+lb.size()+""+lb.get(1).size()+""+"");

        popRecyclerAdapter = new PopRecyclerAdapter( arrayList);
        popRecyclerView.setAdapter(popRecyclerAdapter);

        popupWindow.showAsDropDown(textView);

    }



}